package work.chenbo.spring_boot_shiro.config.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import work.chenbo.spring_boot_shiro.modules.sys_user.entity.SysUser;
import work.chenbo.spring_boot_shiro.modules.sys_user.service.SysUserService;

import java.util.HashSet;
import java.util.Set;

/**
 * 授权领域
 * @author ChenBo
 * @className ShiroRealm
 * @date 2019/10/25
 */
public class ShiroRealm  extends AuthorizingRealm {

    @Autowired
    private SysUserService userService;

    /**
     * 获取授权信息
     * @author ChenBo
     * @date 2019/10/25
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
       if(principals==null){
           throw new AuthorizationException("PrincipalCollection method argument cannot be null!");
       }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Object object = getAvailablePrincipal(principals);
        if(object instanceof SysUser){
            SysUser sysUser = (SysUser) object;
            authorizationInfo.setRoles(sysUser.getStringRoles());
            authorizationInfo.setStringPermissions(sysUser.getStringPermissions());
        }else {
            throw new ClassCastException("Cannot be converted to SysUser!");
        }
        return authorizationInfo;
    }

    /**
     * 获取身份信息
     * @author ChenBo
     * @date 2019/10/25
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String userName = usernamePasswordToken.getUsername();

        if(userName==null){
            throw new AccountException("Null userName are not allowed by this realm!");
        }
        SysUser sysUser = userService.findByUserName(userName);
        if(sysUser==null){
            throw new UnknownAccountException("No account found for user["+userName+"]");
        }

        String credentials = sysUser.getPassword(); //证书 数据库存储
        ByteSource credentialsSalt = ByteSource.Util.bytes(sysUser.getUserName()); //盐值

        return new SimpleAuthenticationInfo(sysUser,credentials,credentialsSalt,getName());
    }
}
